package org.stone.project.druid.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.stone.project.common.pojo.exception.ServiceException;
import org.stone.project.druid.pojo.prop.DruidProperties;
import org.stone.project.dynamicDataSource.config.DynamicDataSource;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * druid 配置多数据源
 */
@Component
@Configuration
public class DruidConfig {
    @Autowired
    private Environment environment;

    /**
     * 根据此属性，加载不同的数据源到容器中
     */
    @Value("#{'${spring.datasource.datasourceListStr}'.split(',')}")
    private List<String> datasourceList;

    @Value("${spring.datasource.dataSourceName}")
    private String dataSourceName;

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DruidProperties druidProperties)
    {
        Map<Object, Object> dsMap = new LinkedHashMap<>();
        if (CollectionUtil.isEmpty(datasourceList)){
            throw new RuntimeException("数据源名称列表为空");
        }
        for (String dsName : datasourceList) {
            DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
            String url = environment.getProperty("spring.datasource.druid.datasource." + dsName + ".url");
            String username = environment.getProperty("spring.datasource.druid.datasource." + dsName + ".username");
            String password = environment.getProperty("spring.datasource.druid.datasource." + dsName + ".password");
            String driverClassName = environment.getProperty("spring.datasource.druid.datasource." + dsName + ".driverClassName");
            if (ObjectUtil.isEmpty(url)  || ObjectUtil.isEmpty(username)|| ObjectUtil.isEmpty(password))
                throw new RuntimeException("数据源为"+dsName+"配置信息为空");
            DruidDataSource druidDataSource = druidProperties.dataSource(dataSource);
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(username);
            druidDataSource.setPassword(password);
            druidDataSource.setDriverClassName(driverClassName);
            dsMap.put(dsName,druidDataSource);
        }
        if (ObjectUtil.isNull(dsMap.get(dataSourceName)))
            throw new ServiceException("数据源不存在");

        return new DynamicDataSource(dataSourceName,dsMap);
    }
}
